import React from 'react';
import { Link } from 'react-router-dom';
import { List, Card, Space, Tag, Button, Typography, Tooltip, Badge, message } from 'antd';
import { DownloadOutlined, EyeOutlined, UserOutlined, ClockCircleOutlined, ArrowUpOutlined, ArrowDownOutlined } from '@ant-design/icons';
import { torrents } from '../../services';

const { Text, Title } = Typography;

const TorrentList = ({ torrents: torrentList = [] }) => {
  // 时间格式化回退函数
  const formatTimeAsFallback = (timeString) => {
    if (!timeString) return '未知时间';

    try {
      const date = new Date(timeString);

      if (isNaN(date.getTime())) {
        return '时间格式错误';
      }

      const now = new Date();
      const diffMs = now.getTime() - date.getTime();
      const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
      const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
      const diffMinutes = Math.floor(diffMs / (1000 * 60));

      // 相对时间显示
      if (diffMinutes < 60) {
        return diffMinutes <= 0 ? '刚刚' : `${diffMinutes}分钟前`;
      } else if (diffHours < 24) {
        return `${diffHours}小时前`;
      } else if (diffDays < 7) {
        return `${diffDays}天前`;
      } else if (diffDays < 30) {
        const weeks = Math.floor(diffDays / 7);
        return `${weeks}周前`;
      } else if (diffDays < 365) {
        const months = Math.floor(diffDays / 30);
        return `${months}个月前`;
      } else {
        const years = Math.floor(diffDays / 365);
        return `${years}年前`;
      }
    } catch (error) {
      console.warn('时间格式化失败:', timeString, error);
      return '时间解析失败';
    }
  };

  // 格式化完整日期时间回退函数
  const formatFullDateTimeAsFallback = (timeString) => {
    if (!timeString) return '未知时间';

    try {
      const date = new Date(timeString);

      if (isNaN(date.getTime())) {
        return '时间格式错误';
      }

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');

      return `${year}年${month}月${day}日 ${hours}:${minutes}`;
    } catch (error) {
      console.warn('完整时间格式化失败:', timeString, error);
      return '时间解析失败';
    }
  };

  const handleDownload = async (torrent) => {
    try {
      // 构造torrentURL，从种子对象中获取或根据ID生成
      const torrentURL = torrent.torrentUrl ||
        torrent.torrentURL ||
        torrent.tResource ||
        `torrent_file/${torrent.id}.${torrent.title || 'file'}.torrent`;

      // 确保传递种子ID给后端用于记录下载次数
      await torrents.downloadTorrent(torrentURL, torrent.id);
      message.success('种子文件下载成功');
    } catch (error) {
      console.error('下载失败:', error);
      message.error('下载失败: ' + error.message);
    }
  };

  // 确保torrentList是数组格式
  const safeDataSource = Array.isArray(torrentList) ? torrentList : [];

  return (
    <List
      grid={{ gutter: 16, column: 3 }}
      dataSource={safeDataSource}
      renderItem={(torrent) => (
        <List.Item>
          <Badge.Ribbon
            text={`${torrent.seeders} 做种`}
            color={torrent.seeders > 100 ? 'green' : torrent.seeders > 50 ? 'blue' : 'orange'}
          >
            <Card
              hoverable
              cover={
                <div style={{
                  height: 220,
                  background: `url(${torrent.coverImage}) center/cover no-repeat`,
                  position: 'relative'
                }}>
                  <div style={{
                    position: 'absolute',
                    bottom: 0,
                    left: 0,
                    right: 0,
                    padding: '5px 10px',
                    background: 'rgba(0,0,0,0.7)',
                    color: 'white'
                  }}>
                    <Tag color="blue">{torrent.category}</Tag>
                    {/* 促销标签 */}
                    {torrent.promotion && torrent.promotion !== 'none' && (
                      <Tag
                        color={
                          torrent.promotion === 'double_upload' ? 'green' :
                            torrent.promotion === 'free_download' ? 'orange' :
                              'purple'
                        }
                        style={{
                          fontWeight: 'bold',
                          fontSize: '11px',
                          padding: '2px 6px',
                          borderRadius: '4px'
                        }}
                      >
                        {torrent.promotion === 'double_upload' ? '⬆️ 双倍上传' :
                          torrent.promotion === 'free_download' ? '🆓 下载免费' :
                            `🎯 ${torrent.promotion}`}
                      </Tag>
                    )}
                    <Text style={{ color: 'white' }}>{torrent.size}</Text>
                  </div>
                </div>
              }
              actions={[
                <Tooltip title="查看详情">
                  <Link to={`/torrent/${torrent.id}`}>
                    <Button type="text" icon={<EyeOutlined />}>详情</Button>
                  </Link>
                </Tooltip>,
                <Tooltip title="下载种子">
                  <Button
                    type="text"
                    icon={<DownloadOutlined />}
                    onClick={() => handleDownload(torrent)}
                  >
                    下载
                  </Button>
                </Tooltip>
              ]}
            >
              <Card.Meta
                title={
                  <Link to={`/torrent/${torrent.id}`}>
                    <Tooltip title={torrent.title}>
                      <div style={{
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis'
                      }}>
                        {torrent.title}
                      </div>
                    </Tooltip>
                  </Link>
                }
                description={
                  <div>
                    <div style={{
                      height: '3em',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      marginBottom: 10
                    }}>
                      {torrent.description}
                    </div>
                    <Space style={{ marginTop: 8 }} wrap>
                      {(torrent.tags || []).map(tag => (
                        <Tag key={tag}>{tag}</Tag>
                      ))}
                    </Space>
                    <div style={{ marginTop: 12 }}>
                      <Space split={<span style={{ margin: '0 8px' }}>|</span>}>
                        <Space>
                          <UserOutlined /> {torrent.uploader}
                        </Space>
                        <Space>
                          <ClockCircleOutlined />
                          <Tooltip title={
                            torrent.fullUploadDateTime ||
                            formatFullDateTimeAsFallback(torrent.uploadDate)
                          }>
                            {torrent.formattedUploadDate || formatTimeAsFallback(torrent.uploadDate)}
                          </Tooltip>
                        </Space>
                        <Space>
                          <DownloadOutlined /> {torrent.downloads || 0}
                        </Space>
                        <Space>
                          <EyeOutlined /> {torrent.views || 0}
                        </Space>
                      </Space>
                    </div>
                  </div>
                }
              />
            </Card>
          </Badge.Ribbon>
        </List.Item>
      )}
    />
  );
};

export default TorrentList;